#TODO: clean up entire controller, very ugly!

include RespondsToParent

class SellController < ApplicationController
  before_filter :login_required
  before_filter :progress_data
  #layout false

  def progress_data
    @progress_steps = [ "Beskrivning", "Bilder", "Kategori", "Annonstyp och pris", "Frakt och betalsätt", "Slutför" ]
    @progress_title = "Skapa ny annons"
    @progress_step = session[:progress_step]
    begin
      if (session[:progress_step] > session[:progress_maxstep])
        session[:progress_maxstep] = session[:progress_step]
      end
    rescue
    
    end
    @progress_maxstep = session[:progress_maxstep]
    #logger.debug("prog_data session[:progress_step] = #{session[:progress_step]}")

  end

  def guide
    if params[:id] == "next"
      session[:progress_step] += 1
    elsif params[:id] == "prev"
      session[:progress_step] -= 1
    elsif params[:id] == "curr"
      
    elsif params[:id]
      session[:progress_step] = params[:id].to_i
    end
#logger.debug("guide m session[:progress_step] = #{session[:progress_step]}")
    if session[:progress_step] == 0
      redirect_to :action => "description"
    elsif session[:progress_step] == 1
      redirect_to :action => "images"
    elsif session[:progress_step] == 2
      redirect_to :action => "categories"
    elsif session[:progress_step] == 3
      redirect_to :action => "type_guide"
    elsif session[:progress_step] == 4
      redirect_to :action => "shipping"
    elsif session[:progress_step] == 5
      redirect_to :action => "preview"
    end
  end

  def new
    @progress_step = @progress_maxstep = session[:progress_step] = session[:progress_maxstep] = 0

    session[:ad] = Ad.new
    session[:ad].enddate = 7.days.from_now unless session[:ad].enddate
    session[:ad_type] = nil
    session[:adcreation_images] = Hash.new
    session[:adcreation_categories] = Hash.new
    session[:adcreation_type] = "type_select"
    session[:auction] = Auction.new
    session[:dynamic_auction] = DynamicAuction.new
    session[:fixed] = Fixed.new
    session[:relaxed] = Relaxed.new
    session[:payment_methods_selected] = Hash.new
    session[:shipping_method_areas_selected] = Array.new
    session[:adcreation_mode] = "new"

    @ad = session[:ad]
  end

  def edit
    @progress_step = session[:progress_step] = 0
    @progress_maxstep = session[:progress_maxstep] = 99

    @ad = Ad.find(params[:id])
    session[:ad] = @ad
    session[:ad_type] = @ad.ad_type
    session[:adcreation_images] = @ad.pictures_hash
    session[:adcreation_categories] = @ad.categories_hash
    if (@ad.auction && @ad.auction.dynamic_auction && @ad.auction.fixed)
      session[:adcreation_type] = "type_form_fixed_dynamic"
    elsif (@ad.auction && @ad.auction.dynamic_auction)
      session[:adcreation_type] = "type_form_dynamic"
    elsif (@ad.auction && @ad.auction.fixed)
      session[:adcreation_type] = "type_form_fixed_auction"
    elsif (@ad.relaxed)
      session[:adcreation_type] = "type_form_relaxed"
    elsif (@ad.auction)
      session[:adcreation_type] = "type_form_auction"
    elsif (@ad.fixed)
      session[:adcreation_type] = "type_form_fixed"
    end
    session[:ad] = @ad
    session[:auction] = @ad.auction if @ad.auction
    session[:dynamic_auction] = @ad.auction.dynamic_auction if @ad.auction
    session[:fixed] = @ad.fixed if@ad.fixed
    session[:fixed] = @ad.auction.fixed if @ad.auction && @ad.auction.fixed
    session[:relaxed] = @ad.relaxed if @ad.relaxed
    session[:payment_methods_selected] = @ad.payment_hash
    session[:shipping_method_areas_selected] = @ad.ad_shipping_methods
    session[:adcreation_mode] = "edit"

    render :partial => "edit"
  end

  def description
    if params[:ad]
      session[:ad].attributes = params[:ad]
      if session[:ad].valid?
        redirect_to :action => "guide", :id => "next"
      end
    end
    @ad = session[:ad]
  end

  def images
    @images = {}
    @images_message = "Här kan du välja bilder på din dator att inkludera i annonsen."
    @images_included = Picture.find_all_by_id(session[:adcreation_images].keys)
    user = session[:user]
    @images_excluded = user.pictures - @images_included
  end

  def image_upload
    unless params[:file] == ""
      image = Picture.resize_and_create(params[:file])
      Picture.assign_to_user(session[:user].id, image)
      session[:adcreation_images][image] = true
      @images_included = Picture.find_all_by_id(session[:adcreation_images].keys)
      user = session[:user]
      @images_excluded = user.pictures - @images_included
      @images_message = "Bilden \"#{params[:file].original_filename}\" har lagts till i annonsen."
      @content_partial = "images"
      responds_to_parent do
        render :update do |page|
          page.replace_html 'image_upload', :partial => "image_upload"
          page.replace_html "images_included", :partial => "images_included"
          page.replace_html "images_excluded", :partial => "images_excluded"
        end
      end
    else
      @images_message = "Du måste först välja en bild, sedan trycka på \"Lägg till\"."
      responds_to_parent do
        render :update do |page|
          page.replace_html 'image_upload', :partial => "image_upload"
          page << "$('image_upload').show();$('image_upload_spinner').hide();"
        end
      end
    end
  end

  def image_push
    session[:adcreation_images][params[:id]] = true
    redirect_to :action => :images
  end

  def image_remove
    session[:adcreation_images].delete(params[:id])
    redirect_to :action => :images
  end

  def categories
    @categories = Category.find_by_category_id(0).categories
    @categories_selected = Category.find(session[:adcreation_categories].keys)
  end

  def category_select
    @layer = params[:master]
    @categories_master = params[:category][:id]
    @categories = Category.find_all_by_category_id(params[:category][:id]) unless params[:category][:id] == ""
  end

  def category_save
    begin
      (session[:adcreation_categories][params[:id]] = true) if Category.find(params[:id])
    rescue
    
    end
    @categories = Category.find_by_category_id(0).categories
    @categories_selected = Category.find(session[:adcreation_categories].keys)
  end

  def category_remove
    session[:adcreation_categories].delete(params[:id])
    @categories = Category.find(session[:adcreation_categories].keys)
  end

  def type_guide
    if params[:reset]
      session[:ad_type] = nil
    end

    if session[:ad_type]
      redirect_to :action => :type_edit
    end

    type_guide_step
  end

  def type_guide_step
    @main_types = Array.new
    @atomic_types = Array.new
    
    if params[:main_type]
      if params[:main_type] == "auction"
        @atomic_types.push(AdType.find_by_name("auction_traditional"))
        @atomic_types.push(AdType.find_by_name("auction_dynamic"))
      elsif params[:main_type] == "fixed"
        @atomic_types.push(AdType.find_by_name("fixed_traditional"))
        @atomic_types.push(AdType.find_by_name("fixed_relaxed"))
      elsif params[:main_type] == "fixed_auction"
        @atomic_types.push(AdType.find_by_name("fixed_auction_traditional"))
        @atomic_types.push(AdType.find_by_name("fixed_auction_dynamic"))
      end
    else
      @main_types.push(AdType.find_by_name("auction"))
      @main_types.push(AdType.find_by_name("fixed"))
      @main_types.push(AdType.find_by_name("fixed_auction"))
    end
  end

  def type_select
    session[:ad_type] = AdType.find_by_name(params[:id])
    
    redirect_to :action => :type_edit
  end

  def type_edit
    @ad = session[:ad]
    @ad_type = session[:ad_type]
    @auction = session[:auction]
    @dynamic_auction = session[:dynamic_auction]
    @fixed = session[:fixed]
    @relaxed = session[:relaxed]
  end

  def type_save
    any_error = false

    logger.debug("check ad #{session[:ad].enddate}")
    if params[:ad]
      new_ad = Ad.new(params[:ad])
      logger.debug("new ad #{new_ad.enddate}")
      session[:ad].enddate = new_ad.enddate
      session[:ad].ad_type = session[:ad_type]
      logger.debug("checked ad #{session[:ad].enddate}")
      unless session[:ad].valid?
        any_error = true
      end
    end

    if params[:auction]
      session[:auction].attributes = params[:auction]
      unless session[:auction].valid?
        any_error = true
      end
    else
      session[:auction] = nil
    end

    if params[:dynamic_auction]
      session[:dynamic_auction].attributes = params[:dynamic_auction]
      unless session[:dynamic_auction].valid?
        any_error = true
      end
    end

    if params[:fixed]
      session[:fixed].attributes = params[:fixed]
      unless session[:fixed].valid?
        any_error = true
      end
    end

    if params[:relaxed]
      session[:relaxed].attributes = params[:relaxed]
      unless session[:relaxed].valid?
        any_error = true
      end
    end

    if (any_error)
      redirect_to :action => "type_guide"
    else
      redirect_to :action => "guide", :id => "next"
    end
  end

  def shipping
    @payment_methods_available = PaymentMethod.find(:all)
    @payment_methods_selected = session[:payment_methods_selected]
    @shipping_methods_available = ShippingMethod.find(:all)
    @shipping_areas_available = ShippingArea.find(:all)
    @shipping_method_areas_selected = session[:shipping_method_areas_selected]
  end

  def payment_change
    if (session[:payment_methods_selected].has_key?(params[:id].to_i))
      session[:payment_methods_selected].delete(params[:id].to_i)
    else
      session[:payment_methods_selected][params[:id].to_i] = true
    end
    render :nothing => true
  end

  def shipping_add
    method_area = AdShippingMethod.new(params[:ad_shipping_method])
    session[:shipping_method_areas_selected].push(method_area)
    @shipping_method_areas_selected = session[:shipping_method_areas_selected]
    @shipping_methods_available = ShippingMethod.find(:all)
    @shipping_areas_available = ShippingArea.find(:all)
  end

  def shipping_remove
    session[:shipping_method_areas_selected].delete_at(params[:id].to_i)
    @shipping_method_areas_selected = session[:shipping_method_areas_selected]
    @shipping_methods_available = ShippingMethod.find(:all)
    @shipping_areas_available = ShippingArea.find(:all)
  end

  def preview
    @images_included = Picture.find_all_by_id(session[:adcreation_images].keys)
    @categories_selected = Category.find(session[:adcreation_categories].keys)
    @payment_methods_selected = PaymentMethod.find(session[:payment_methods_selected].keys)
    @shipping_method_areas_selected = session[:shipping_method_areas_selected]

    @ad_type_name = AdType.find(session[:ad_type]).name
    
  end

  def finish
    #update/save the actual ad
    ad = session[:ad]
    ad.user_id = session[:user].id
    ad.start = Time.now
    ad.save

    #save images
    images_included = ad.pictures
    images_tobeincluded = Picture.find_all_by_id(session[:adcreation_images].keys) - images_included
    images_tobeexcluded = images_included - Picture.find_all_by_id(session[:adcreation_images].keys)

    images_tobeincluded.each { |p| Gallery.create(:picture_id => p.id, :ad_id => ad.id) }
    images_tobeexcluded.each { |p| Gallery.delete_all("picture_id = '#{p.id}' and ad_id = '#{ad.id}'") }


    #save categories
    categories_included = ad.categories
    categories_tobeincluded = Category.find_all_by_id(session[:adcreation_categories].keys) - categories_included
    categories_tobeexcluded = categories_included - Category.find_all_by_id(session[:adcreation_categories].keys)

    categories_tobeincluded.each { |c| AdCategory.create(:ad_id => ad.id, :category_id => c.id) }
    categories_tobeexcluded.each { |c| AdCategory.delete_all("ad_id = '#{ad.id}' and category_id = '#{c.id}'") }


    #update/save auction type
    #logger.debug("session[:adcreation_type] = #{session[:adcreation_type]}")

    ad_type_name = AdType.find(session[:ad_type]).name

    if (ad_type_name == "auction_traditional")
      session[:auction].ad_id = ad.id
      session[:auction].save
    elsif (ad_type_name == "auction_dynamic")
      session[:auction].ad_id = ad.id
      session[:auction].save
      session[:dynamic_auction].auction_id = session[:auction].id
      session[:dynamic_auction].save
    elsif (ad_type_name == "fixed_traditional")
      session[:fixed].save
      begin
        FixedAd.create(:ad_id => ad.id, :fixed_id => session[:fixed].id)
      rescue
      end
    elsif (ad_type_name == "fixed_auction_traditional")
      session[:fixed].quantity = 1
      session[:fixed].save
      session[:auction].ad_id = ad.id
      session[:auction].save
      begin
        FixedAuction.create(:auction_id => session[:auction].id, :fixed_id => session[:fixed].id)
      rescue
      end
    elsif (ad_type_name == "fixed_auction_dynamic")
      session[:fixed].quantity = 1
      session[:fixed].save
      session[:auction].ad_id = ad.id
      session[:auction].save
      fixed_auction = FixedAuction.new
      fixed_auction.auction_id = session[:auction].id
      fixed_auction.fixed_id = session[:fixed].id
      fixed_auction.save
      session[:dynamic_auction].auction_id = session[:auction].id
      session[:dynamic_auction].save
    elsif (ad_type_name == "fixed_relaxed")
      session[:relaxed].ad_id = ad.id
      session[:relaxed].save
    end


    #shipping
    shipping_included = ad.ad_shipping_methods
    shipping_tobeincluded = session[:shipping_method_areas_selected] - shipping_included
    shipping_tobeexcluded = shipping_included - session[:shipping_method_areas_selected]

    shipping_tobeincluded.each { |c| AdShippingMethod.create(:ad_id => ad.id, :shipping_method_id => c.shipping_method_id, :shipping_area_id => c.shipping_area_id, :price => c.price) }
    shipping_tobeexcluded.each { |c| AdShippingMethod.delete_all("ad_id = '#{ad.id}' and shipping_method_id = '#{c.shipping_method_id}' and shipping_area_id = '#{c.shipping_area_id}'") }


    #payment
    payment_included = ad.payment_methods
    payment_tobeincluded = PaymentMethod.find_all_by_id(session[:payment_methods_selected].keys) - payment_included
    payment_tobeexcluded = payment_included - PaymentMethod.find_all_by_id(session[:payment_methods_selected].keys)
    payment_tobeincluded.each { |c| AdPaymentMethod.create(:ad_id => ad.id, :payment_method_id => c.id) }
    payment_tobeexcluded.each { |c| AdPaymentMethod.delete_all("ad_id = '#{ad.id}' and payment_method_id = '#{c.id}'") }


    #set status to visible
    ad = session[:ad]
    ad.ad_status_id = 1
    ad.save

    ad.categories.each do |c|
      Event.create(:event_type_id => 5, :primary_subject => c.id, :secondary_subject => ad.id)
    end

    #Go to user home page
    redirect_to "/private/show"
  end
end
